package com.func.domain.strategy.service.rule.tree.impl;

import com.func.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.func.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.armory.IStrategyDispatch;
import com.func.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.func.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @version 1.0
 * @className RuleStockLogicTreeNode
 * @description 规则树节点-库存检验规则
 * @author: func
 * @date 2025/2/28 21:21
 */

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    /**
     * 更新库存奖品的库存
     * @param userId
     * @param strategyId
     * @param awardId    前面抽奖得到的奖品Id
     * @return  返回是否更新成功的TreeAction
     */
    @Resource
    protected IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId : {}, strategyId : {}, awardId : {}", userId, strategyId, awardId);
        // 从缓存中更新奖品库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);
        if (status) {
            log.info("规则过滤-库存扣减-成功-放行 userId : {}, strategyId : {}, awardId : {}", userId, strategyId, awardId);
            // 更新成功, 将更新数据库记录的任务写入到Redis的延迟队列中
            repository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        log.info("规则过滤-库存扣减-失败-接管 userId : {}, strategyId : {}, awardId : {}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
